package com.eliauk.demo.controller.read;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.eliauk.demo.entity.read.DemoData;
import com.eliauk.demo.utils.excel.listener.Demo3DataListener;
import com.eliauk.demo.utils.excel.listener.Demo1DataListener;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping("/demo3")
public class demo3Controller {

    /**
     * 读取多个sheet
     * @param file excel 文件
     * @return
     * @throws IOException
     */
    @PostMapping("/import")
    public String importData(MultipartFile file) throws IOException {
        InputStream in  = file.getInputStream();
        // 读取全部sheet
        // 这里需要注意 DemoDataListener的doAfterAllAnalysed 会在每个sheet读取完毕后调用一次。然后所有sheet都会往同一个DemoDataListener里面写
        EasyExcel.read(in, DemoData.class, new Demo3DataListener()).excelType(ExcelTypeEnum.XLSX).doReadAll();
        try (ExcelReader excelReader = EasyExcel.read(in).build()) {
            // 这里为了简单 所以注册了 同样的head 和Listener 自己使用功能必须不同的Listener
            ReadSheet readSheet1 = EasyExcel.readSheet(0).head(DemoData.class).registerReadListener(new Demo1DataListener()).build();
            ReadSheet readSheet2 = EasyExcel.readSheet(1).head(DemoData.class).registerReadListener(new Demo1DataListener()).build();
            // 这里注意 一定要把sheet1 sheet2 一起传进去，不然有个问题就是03版的excel 会读取多次，浪费性能
            excelReader.read(readSheet1, readSheet2);
        }
        return "success";
    }
}
